// pages/me/coupon/coupon.js
import { Api } from "../../../utils/api.js"
import { Http } from '../../../utils/http.js'
import { TimeToDate } from '../../../utils/timeToDate.js'
let http = new Http()
let timeToDate = new TimeToDate()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageNum: 1,
    pageSize: 6,
    pages: 1,
    coupons: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      pageNum: 1,
      pageSize: 6,
      pages: 1,
      coupons: []
    })
    this.getMyCoupons()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.getMyCoupons()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 自定义方法
   */
  getMyCoupons: function () {
    var that = this
    var pageNum = this.data.pageNum
    var pageSize = this.data.pageSize
    var pages = this.data.pages
    if (pageNum <= pages) {
      http.sendHttp(Api.get_my_coupons, {
          data: {
            pageNum: pageNum,
            pageSize: pageSize
          },
          success: function (res) {
            var coupons = res.data.obj.coupons
            for (var index in coupons) {
              coupons[index].tmExpire = timeToDate.formatTime(coupons[index].tmExpire / 1000, 'Y-M-D')
            }
            that.setData({
              coupons: that.data.coupons.concat(coupons),
              pages: res.data.obj.pages,
              pageNum: pageNum + 1
            })
          }
        })
      }
    }
})